package com.cheeven.amazonbooksreviewscores;

import java.io.FileWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class GetTop100 {

    public static void main(String[] args) throws Exception {

        String nextPageUrl = "http://www.amazon.com/gp/bestsellers/2010/books/ref=zg_bsar_cal_mo";
        String fileName = "top100.txt";
        
        if(args.length>0) {
            nextPageUrl = args[0];
        }
        if(args.length>1) {
            fileName = args[1];
        }

        GetTop100 rc = new GetTop100();

        PrintWriter output = new PrintWriter(new FileWriter(fileName));

        rc.analyseOnePage(nextPageUrl, output, true);

        output.close();
    }

    public void analyseOnePage(String urlString, PrintWriter output, boolean isFirstPage) throws Exception {
        GetPage page = new GetPage();
        Document domdoc = page.getPageDOM(new URL(urlString));

        Element zgList = page.getPageInfoElement(domdoc, "//div[@id='zg_list']");

        NodeList zgItems = page.getPageInfoNodeList(zgList, "ol/li/div[@class='zg_item zg_sparseListItem']");
        for (int i = 0; i < zgItems.getLength(); i++) {
            Element zgItem = (Element) zgItems.item(i);

            HashMap<String, String> book = new HashMap<String, String>();
            book.put("asin", zgItem.getAttribute("asin"));
            book.put("rank", page.getPageInfo(zgItem, "div[@class='zg_rankInfo']"));
            book.put("image", page.getPageInfo(zgItem, "div[@class='zg_image']/a/img/@src"));

            Element zgItemInfo = page.getPageInfoElement(zgItem, "div[@class='zg_itemInfo']");
            if (zgItemInfo != null) {
                book.put("title", page.getPageInfo(zgItemInfo, "div[@class='zg_title']"));
                book.put("url", page.getPageInfo(zgItemInfo, "div[@class='zg_title']/a/@href"));
            }

            System.out.println(book);

            output.print(book.get("rank") + "\t");
            output.print(book.get("asin") + "\t");
            output.print(book.get("title") + "\t");
            output.print(book.get("url") + "\t");
            output.print(book.get("image") + "\t");
            output.println();

        }

        output.flush();

        if (isFirstPage == true) {
            for (int j = 2; j <= 5; j++) {
                Element zgPage = page.getPageInfoElement(domdoc, "//li[@id='zg_page" + j + "']");
                String nextPageUrl = (zgPage == null) ? null : page.getPageInfo(zgPage, "a/@href");
                System.out.println(nextPageUrl);
                if (nextPageUrl != null) {
                    analyseOnePage(nextPageUrl, output, false);
                }
            }
        }

    }
}
